package com.yunao.web.controller;

import com.yunao.commons.enums.ArticleType;
import com.yunao.commons.serachcore.core.bean.Articles;
import com.yunao.commons.utils.ResultVOUtil;
import com.yunao.commons.vo.ResultVO;
import com.yunao.entity.ArticleItem;
import com.yunao.entity.User;
import com.yunao.service.ArticleService;
import com.yunao.service.UserService;
import com.yunao.service.report.Convert;
import com.yunao.service.report.ExcelWriter;
import com.yunao.service.report.ExcelWriterItem;
import com.yunao.web.annotation.UserLoginToken;
import com.yunao.web.convert.QueryForm2Map;
import com.yunao.web.form.QueryForm;
import com.yunao.web.utils.TokenUtil;
import com.zhongsou.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/favorite/favorite/")
public class FavoriteController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @RequestMapping("/findOne")
    public ResultVO querybyId(Integer id) {
        return ResultVOUtil.success(articleService.findOne(id));
    }

    @RequestMapping("/findByQuery")
    public ResultVO findByQuery(@RequestParam(value = "days", defaultValue = "3") Integer days,
                                String date,
                                @RequestParam(name = "page", defaultValue = "1") Integer page,
                                @RequestParam(name = "size", defaultValue = "10") Integer size,
                                String word,
                                HttpServletRequest request) throws ParseException {
        String userId = TokenUtil.getTokenUserId();
        Sort sort = new Sort(Sort.Direction.DESC, "articlePubdate");
        Pageable pageable = new PageRequest(page - 1, size, sort);
        Long time = 0l;
        if (StringUtils.isEmpty(word)) {
            if (!StringUtils.isEmpty(date)) {
                time = DateUtil.str2Date(date, "yyyy-MM-dd").getTime();
            } else {
                time = (Long) (new Date().getTime() - days * 24 * 3600 * 1000l);
            }
            return ResultVOUtil.success(articleService.findByQuery(Convert.getInt(userId), ArticleType.FAVORITE.getCode(), new Date(time), "", pageable));
        } else {
            if (!StringUtils.isEmpty(date)) {
                time = DateUtil.str2Date(date, "yyyy-MM-dd").getTime();
            } else {
                time = (Long) (new Date().getTime() - days * 24 * 3600 * 1000l);
            }
            return ResultVOUtil.success(articleService.findByQuery(Convert.getInt(userId), ArticleType.FAVORITE.getCode(), new Date(time), word, pageable));
        }
    }


    @RequestMapping("/list")
    public ResultVO getArticleItems(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "10") Integer size,
                                    HttpServletRequest request) {
        String userId = TokenUtil.getTokenUserId();
        Sort sort = new Sort(Sort.Direction.DESC, "articlePubdate");
        Pageable pageable = new PageRequest(page - 1, size, sort);

        return ResultVOUtil.success(articleService.getArticleItems(Convert.getInt(userId), ArticleType.FAVORITE.getCode(), pageable));
    }


    @RequestMapping("/alarmArticles")
    public ResultVO getalarmArticles(Integer subjectId,
                                     Integer numday,
                                     String word,
                                     String day,
                                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "size", defaultValue = "10") Integer size,
                                     HttpServletRequest request) {
        String userId = TokenUtil.getTokenUserId();
        Sort sort = new Sort(Sort.Direction.DESC, "articlePubdate");
        Pageable pageable = new PageRequest(page - 1, size, sort);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date numdate = null;
        if (numday != null && !"".equals(numday)) {
            numdate = new Date(System.currentTimeMillis() - numday * 24 * 60 * 60 * 1000);
        }
        Date daydate = null;
        if (StringUtils.isNotEmpty(day)) {
            try {
                daydate = simpleDateFormat.parse(day);
            } catch (ParseException e) {
            }

        }
        return ResultVOUtil.success(articleService.findAlarms(
                Convert.getInt(userId), ArticleType.ALARM.getCode(), word, numdate, daydate, subjectId, pageable));
    }


    @RequestMapping("/popAlarms")
    public ResultVO getpopAlarms(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "size", defaultValue = "10") Integer size,
                                 HttpServletRequest request) {
        Long time = new Date().getTime() - 2 * 60 * 1000l;
        String userId = TokenUtil.getTokenUserId();
        Sort sort = new Sort(Sort.Direction.DESC, "articlePubdate");
        Pageable pageable = new PageRequest(page - 1, size, sort);
        return ResultVOUtil.success(articleService.findAlarms(
                Convert.getInt(userId), ArticleType.ALARM.getCode(), null, null, new Date(time), null, pageable));
    }

    @RequestMapping("/findByWord")
    public ResultVO findByWord(String word) {
        return ResultVOUtil.success(articleService.findByWord("%" + word + "%"));
    }



    @RequestMapping("/deleteById")
    public ResultVO delete(Integer articleId) {
        articleService.deleteById(articleId);
        return ResultVOUtil.success();
    }

    @RequestMapping("/deleteAll")
    public ResultVO deleteAll(String articleIds) {
        articleService.deleteByIds(articleIds);
        return ResultVOUtil.success();
    }

    @RequestMapping("/exportbyids")
    public ResultVO exportbyids(@RequestParam(name = "ids",required = false) String ids,
                                @RequestParam(name = "type",required = true)Integer type,
                                HttpServletResponse response) throws FileNotFoundException {
        List<ArticleItem> articleItems = new ArrayList<>();
        if (StringUtils.isEmpty(ids)){
            User user = TokenUtil.getTokenUser(userService);
            articleItems = articleService.findByUserAndType(user.getUserId(),type);
        }else {
            articleItems = articleService.findAllById(ids);
        }
        // 导出文件夹存放导出文件的临时文件
        String path = System.getProperty("user.dir").replace("bin", "webapps") + "\\export\\";
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        // 导出文件 文件名称
        file = new File(path + System.currentTimeMillis() + ".xls");
        // 保存为临时文件
        OutputStream out = new FileOutputStream(file);
        ExcelWriterItem writer = new ExcelWriterItem(articleItems, out);
        writer.write();
        String fileName = "Esou_Export_Execl.xls";
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        BufferedOutputStream bufo = null;
        try {
            bufo = new BufferedOutputStream(response.getOutputStream());
            InputStream in = new FileInputStream(file);
            int read = 0;
            byte[] tempbytes = new byte[1024];
            while ((read = in.read(tempbytes)) != -1) {
                bufo.write(tempbytes, 0, read);
                bufo.flush();
            }
        } catch (Exception e) {

        } finally {
            try {
                if (bufo != null)
                    bufo.close();
            } catch (Exception e) {

            }
        }
        return ResultVOUtil.success();
    }


    @RequestMapping("/saveList")
    @Transactional
    public ResultVO saveList(@RequestParam String ids, HttpServletRequest request) {
//        List<String> idList = Arrays.asList(ids.split(","));
        User userOutput = TokenUtil.getTokenUser(userService);
        Articles articles = articleService.seachByids(ids);
        articleService.save(articles, userOutput);
        return ResultVOUtil.success();
    }


}
